import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { HttpClient } from '@angular/common/http';
import { GisDataUtils } from 'src/app/base/gis/data/gis.data';
import { element } from 'protractor';

declare var base: any;
declare var form: any;
declare var map: any;
declare var echarts: any;

@Component({
  selector: 'overlay-analysis',
  templateUrl: './analysis.component.html',
  styleUrls: ['./analysis.component.scss']
})
export class AnalysisComponent implements OnInit {

  // 配置表单服务
  fs: any;
  // 文件分析服务
  ffs: any;
  // 字典服务
  ds: any;
  // 字典翻译服务
  de: any;
  // 打印服务
  pr: any;
  // 配置所属元数据
  metedata: string;
  // 叠加分析服务
  oa: any = { gas: {} };
  // 高亮服务
  renderService: any;
  // 基础路径
  baseUrl: string;
  // 是否展示分析结果
  analysis = false;
  // 高亮参数
  option: any;
  // 重置加载中
  isLoading = false;
  // 统计字段
  statisticsField: string;
  // 是否初始化
  isInit = false;
  // 上传的文件
  files = [];
  pageList: any;

  // 统计类型名
  statisticsCateoryName = '';
  // 统计字段名
  statisticsFieldName = '';
  // 统计列表
  statisticsList = [];
  // 导出是否完成
  exportIsLoading = false;

  // 导出数据
  exportData = { currentGm: [], intersectGm: [], showDisplay: [], showValue: [], statisticsDisplay: [], statisticsValue: [] };

  // source ID
  sourceId = 'analysis_Polygon';
  // source
  source: any;
  // layer Id
  layerId = 'analysis_layer';

  resultSource: any;

  constructor(
    private message: NzMessageService, private http: HttpClient
  ) {

    this.ffs = new form.FileService();
    this.ds = new form.DictionaryService('g_analysis_config', this.filter);
    this.de = form.FormDataService;
    this.fs = new form.FormSimpleService('analysisconfig', {
      orderObject: { order: 0 },
      keyField: 'id',
      randomFields: ['id'],
      queryFields: '*'
    });
    this.pr = form.PrintService;

    this.baseUrl = base.BaseService.getHostUrl();

  }

  filter(data) {
    if (data) {
      const ri = [];
      for (let i = data.length - 1; i >= 0; i--) {
        const e = data[i];
        if (e.info === '2' || e.info === '3') {
          ri.push(i);
        }
        if (e.valid === false) {
          ri.push(i);
        }
      }
      ri.forEach((j) => {
        data.splice(j, 1);
      });
      return data;
    }
  }

  ngOnInit() {

  }

  // 初始化分析服务
  initOaService(callback: any) {
    map.Factory.SpatialAnalysis('OverlayAnalysis', (overlayAnalysis) => {
      // 初始化查询对象
      overlayAnalysis.initSearchForm();

      this.oa = overlayAnalysis;
      this.isInit = true;

      if (callback) {
        callback(overlayAnalysis);
      }
    });
  }

  iChange(item) {
    if (this.isInit === false) {
      const that = this;
      this.initOaService((o) => {
        that.change(item);
      });
    } else {
      this.change(item);
    }
  }

  /**
   * 分析图层选中值改变
   */
  change(item): void {
    const result = this.oa;
    const searchInfo = this.oa.gas;
    // 清空查询值
    searchInfo.statisticsCateory = null;
    searchInfo.statisticsField = [];
    searchInfo.showField = [];
    // 先清空数组
    result.categorysDic = [];
    result.statisticsDic = [];
    result.showDic = [];
    // 定义对象
    const data = this.ds.datas;
    if (data) {
      data.forEach(e => {
        if (item === e['id'] && e['other']) {
          result.categorysDic = e['other']['statisticsCateory'];
          result.statisticsDic = e['other']['statisticsField'];
          e['other']['showField'].forEach(element => {
            searchInfo.showField.push(element.value);
          });
          result.showDic = e['other']['showField'];
        }
      });
    }

    this.fs.defaultQueryObject = { id: item };

  }

  iUploadOption(obj) {
    if (this.isInit === false) {
      const that = this;
      this.initOaService((o) => {
        that.uploadOption(obj);
      });
    } else {
      this.uploadOption(obj);
    }
  }

  // 文件上传后处理
  uploadOption(obj) {
    if (obj.type === 'success') {
      obj.fileList.splice(0, obj.fileList.length - 1);
      if (obj.file.response && obj.file.response.code === '-1') {

        const wktStr = obj.file.response.data;

        if (wktStr.length === 0) {
          this.message.error('该文件未包含空间信息');
          return;
        }

        const geojson = {
          type: 'FeatureCollection',
          features: []
        };

        // 先清除相关图层
        if (this.source) {
          this.source.setData(geojson);
        }

        // 初始化geometry数据
        this.oa.gas.geometry = [];
        // 初始化数据
        this.iReset();

        wktStr.some((e, index) => {
          map.Factory.Utils('TerraformerUtils', (terraformerUtils) => {
            const geometry = terraformerUtils.WktToGeoGeometry(e);
            if (geometry) {
              this.oa.gas.geometry.push(e);

              // 坐标系校验
              const valid = this.validateSrs(geometry);
              if (index === 0 && valid === true) {
                this.oa.gas.featureType = this.oa.getFeatureType(e);
              } else if (index === 0 && valid === false) {
                return true;
              }

              // 组装数据
              const feature = {
                'type': 'Feature',
                'geometry': geometry
              };
              geojson.features.push(feature);

              if (geojson.features.length === wktStr.length) {
                this.showlayer(geojson);
                this.localPosition(geojson);
              }
            } else {
              this.message.error('解析图形信息失败');
            }

          });
        });
      } else {
        this.message.error(obj.file.response.msg);
      }
    }
  }

  // 定位
  localPosition(geojson: any) {
    map.Factory.Utils('GeojsonUtils', (geojsonUtils) => {
      const bound = geojsonUtils.getGeojsonBoundingBox(geojson);
      if (!this.oa.map && form.ConfigService.map) {
        this.oa.map = form.ConfigService.map;
      }
      this.oa.gas.srs = this.oa.map.mapParam.projection;
      this.oa.map.zoomToExtent(bound);
    });
  }

  // 边框高亮
  showlayer(geojson: any) {
    this.source = this.oa.map.getSource(this.sourceId);
    if (this.source) {
      this.source.setData(geojson);
    } else {
      this.source = this.oa.map.addSource(this.sourceId, {
        'type': 'geojson',
        'data': geojson
      });

      const layer = this.oa.map.addLayer(this.layerId, this.sourceId, {
        'type': 'line',
        "layout": {
          "line-join": 'round',
          "line-cap": 'round'
        },
        "paint": {
          'line-color': '#ff0000',
          'line-width': 3
        }
      });
    }
  }

  // 坐标系校验
  validateSrs(geometry: any) {

    let mapIsGcs = true;
    let uploadIsGcs = true;

    if (!this.oa.map && form.ConfigService.map) {
      this.oa.map = form.ConfigService.map;
    }
    const mapX = this.oa.map.mapParam.fullExtent.xmin;

    // 判断是投影还是经纬度
    if (Number(mapX) > -180 && Number(mapX) < 180) {
      mapIsGcs = true;
    } else {
      mapIsGcs = false;
    }

    const coordinate = geometry.coordinates[0];
    let uploadX = 0;
    if (coordinate[0]) {
      uploadX = coordinate[0];
      if (coordinate[0][0]) {
        uploadX = coordinate[0][0];
        if (coordinate[0][0][0]) {
          uploadX = coordinate[0][0][0];
        }
      }
    }

    // 判断是投影还是经纬度
    if (Number(uploadX) > -180 && Number(uploadX) < 180) {
      uploadIsGcs = true;
    } else {
      uploadIsGcs = false;
    }

    if (mapIsGcs === uploadIsGcs) {
      return true;
    } else {
      this.message.error('请转换坐标系重试');
      return false;
    }

  }

  iStartAnalysis() {
    if (this.isInit === false) {
      const that = this;
      this.initOaService((o) => {
        that.startAnalysis();
      });
    } else {
      this.startAnalysis();
    }
  }

  // 开始分析
  startAnalysis() {

    // 分析成功处理
    this.oa.isLoading = true;
    this.fs.loadData(true, (o) => {
      if (o && o[0]) {
        const po = o[0];
        this.oa.gas.url = po.layerId;
        this.oa.gas.serviceName = po.serviceName;
        this.oa.gas.geoField = po.geoField;
        this.oa.gas.searchServiceType = po.type;
        this.oa.gas.statisticsField[0] = this.statisticsField;
        this.metedata = po.medname;
        this.pageList = [];
        this.statisticsList = [];

        // 根据实际业务场景添加
        // this.oa.gas.filter = "gllx = '10'";

        if (this.oa.gas.buffer >= 0.05) {
          this.message.info('当前需要查询的数据量可能较大请耐心等待');
        }

        // 开始分析
        GisDataUtils.analysis(this.http, this.oa, (o) => {
          if (o.resultAttribute.length > 0 || o.statistics.length > 0) {

            // 开始翻译
            this.dictionaryEscape(this.oa.pageList, (o) => {
              this.pageList = o;
            });

            const statisKindList = this.assembleData(this.oa.statisticsList, true);

            this.dictionaryEscape(statisKindList, (o) => {
              this.statisticsList = this.assembleData(o, false);

              // 初始化图层
              this.initStatisticsCharts();
            });

            // 展示表格
            this.analysis = true;

          } else {
            this.message.warning('没有相交的结果集');
            this.oa.isLoading = false;
          }
        });
      }
    });
  }

  // 字典翻译
  dictionaryEscape(list: any, backcall?: Function) {
    let transCount = 0;
    const pageList = [];
    list.forEach(item => {
      this.de.dictionaryEscape(this.metedata, item, (data) => {
        for (const key in data) {
          if (data.hasOwnProperty(key) === true) {
            if (key.indexOf('_Name') !== -1) {
              const newKey = key.replace('_Name', '');
              data[newKey] = data[key] || '无';
              delete data[key];
            }
          }
        }
        pageList.push(data);
        transCount++;
        if (transCount === list.length) {
          if (backcall) {
            backcall(pageList);
          }

        }
      });
    });
  }

  // 组装统计数据，方便翻译字典
  assembleData(list: any, way: boolean) {
    const key = this.oa.gas.statisticsCateory;
    const newList = [];
    if (way === true) {
      list.forEach(item => {
        const obj = {};
        obj[key] = item[0];
        newList.push(obj);
      });
    } else {
      list.forEach((item, i) => {
        newList.push([item[key], this.oa.statisticsList[i][1]]);
      });
    }
    return newList;
  }

  // 页数改变加载数据
  loadPage() {
    if (this.oa) {
      this.oa.loadPage();
      this.dictionaryEscape(this.oa.pageList, (o) => {
        this.pageList = o;
      });
    }
  }


  layerHighlight(index: number) {
    index = (this.oa.pageSize * (this.oa.pageIndex - 1)) + index;

    this.resultSource = this.oa.map.getSource(this.sourceId + '_1');

    map.Factory.Utils('TerraformerUtils', (terraformerUtils) => {
      const geometry = terraformerUtils.WktToGeoGeometry(this.oa.resultGeometrys[index]);
      if (geometry) {
        if (this.resultSource) {
          index
          this.resultSource.setData(geometry);
        } else {
          this.resultSource = this.oa.map.addSource(this.sourceId + '_1', {
            'type': 'geojson',
            'data': geometry
          });

          this.oa.map.addLayer(this.layerId + '_1', this.sourceId + '_1', {
            'type': 'fill',
            'paint': {
              'fill-color': 'rgba(200, 0, 0, 0.5)',
              'fill-outline-color': '#fbb03b',
              'fill-opacity': 0.8
            },
          });
        }
      }

    });

  }


  clearHighlight() {
    if (this.resultSource) {
      this.resultSource.setData({
        type: 'FeatureCollection',
        features: []
      });
    }
  }



  // 初始化echarts图
  initStatisticsCharts() {
    this.chartsData();

    const statisticsChart = echarts.init(document.getElementById('statistics_chart'));

    statisticsChart.setOption(this.option);

    this.oa.isLoading = false;
  }

  // ecahrts数据处理
  chartsData() {
    const statisticsType = [];
    const statisticsData = [];
    this.oa.categorysDic.forEach(element => {
      if (element.value === this.oa.gas.statisticsCateory) {
        this.statisticsCateoryName = element.label;
      }
    });
    this.oa.statisticsDic.forEach(element => {
      if (element.value === this.oa.gas.statisticsField[0]) {
        this.statisticsFieldName = element.label;
      }
    });
    this.statisticsList.forEach(element => {
      statisticsType.push(element[0]);
    });
    this.statisticsList.forEach(element => {
      const obj = {};
      obj['name'] = element[0];
      obj['value'] = element[1];
      statisticsData.push(obj);
    });

    this.option = {
      // title: {
      //   text: statisticsCateoryName,
      //   // subtext: '统计分析图',
      //   x: 'center'
      // },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: statisticsType
      },
      series: [
        {
          name: this.statisticsCateoryName,
          type: 'pie',
          radius: '55%',
          center: ['50%', '50%'],
          data: statisticsData,
          itemStyle: {
            emphasis: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
  }

  iReset() {
    if (this.isInit === false) {
      const that = this;
      this.initOaService((o) => {
        that.reset();
      });
    } else {
      this.reset();
    }
  }

  // 重置
  reset() {
    if (this.isLoading === true) {
      return;
    }
    this.isLoading = true;

    // 重置数据
    this.oa.reset();
    this.statisticsField = null;
    this.oa.initSearchForm();

    // 清除相关图层
    const geojson = {
      type: 'FeatureCollection',
      features: []
    };
    if (this.source) {
      this.source.setData(geojson);
    }
    if (this.resultSource) {
      this.resultSource.setData(geojson);
    }

    // 隐藏表单
    this.analysis = false;

    // 清除导出数据
    this.clearExportData();
    this.exportIsLoading = false;

    // 重置完成
    this.isLoading = false;
  }

  // 空间数据处理
  geometryData(callback: any) {
    this.clearExportData();
    const currentGeometry = this.oa.currentGeometry;
    const intersectGeometrys = this.oa.intersectGeometrys;

    const that = this;
    map.Factory.Utils('TerraformerUtils', (terraformerUtils) => {

      currentGeometry.forEach(wkt => {
        const geometry = terraformerUtils.WktToGeoGeometry(wkt);
        const datas = [];

        const coordinates = this.specialTreatment(geometry);

        coordinates.forEach(c => {
          const obj = { x: c[0], y: c[1] };
          datas.push(obj);
        });

        that.exportData.currentGm = datas;
      });

      intersectGeometrys.forEach(wkt => {

        const geometry = terraformerUtils.WktToGeoGeometry(wkt);
        const datas = [];
        const coordinates = this.specialTreatment(geometry);

        coordinates.forEach(c => {
          const obj = { x: c[0], y: c[1] };
          datas.push(obj);
        });

        that.exportData.intersectGm.push(datas);
      });

      this.AttrData(callback);

    });
  }


  specialTreatment(geometry: any) {
    // 特殊处理可优化,查询geometry点的位置
    let coordinates = [];
    if (geometry && geometry.coordinates[0]) {
      if (geometry.coordinates[0][0]) {
        coordinates = geometry.coordinates;
        if (geometry.coordinates[0][0][0]) {
          coordinates = geometry.coordinates[0];
          if (geometry.coordinates[0][0][0][0]) {
            coordinates = geometry.coordinates[0][0];
          }
        }
      }
    }

    return coordinates;
  }

  // 属性处理
  AttrData(callback: any) {

    this.oa.showDic.forEach(dic => {
      this.exportData.showDisplay.push(dic.label);
    });

    const page = [];
    this.oa.datas.resultAttribute.forEach(data => {
      for (const key in data) {
        if (data.hasOwnProperty(key) === true) {
          page.push(data[key]);
        }
      }
    });

    this.dictionaryEscape(page, (o) => {
      o.forEach(item => {
        const obj = [];
        for (const key in item) {
          if (item.hasOwnProperty(key) === true) {
            obj.push(item[key]);
          }
        }
        this.exportData.showValue.push(obj);
      });


      this.exportData.statisticsValue = this.statisticsList;

      this.exportData.statisticsDisplay = [this.statisticsCateoryName, this.statisticsFieldName];

      if (callback) {
        callback(this.exportData);
      }
    });

  }


  // 导出word
  exportWord(template: any, filename: any) {

    if (this.exportIsLoading === true) {
      return;
    }

    if (this.analysis === false) {
      this.message.warning('请先进行分析');
      return;
    }

    this.exportIsLoading = true;

    this.geometryData((exportData) => {
      this.pr.printWord(template, filename, exportData, 'true', () => {
        this.exportIsLoading = false;
      });
    });

  }

  clearExportData() {
    this.exportData = { currentGm: [], intersectGm: [], showDisplay: [], showValue: [], statisticsDisplay: [], statisticsValue: [] };
  }


}
